package services

import (
	"HyperNexus/hyperNexus/defines"
	"github.com/ebitengine/purego"
)

type ServiceGo struct {
	Service
	libHandel    uintptr // so库的句柄
	startFunc    defines.StartService
	runFunc      defines.RunService
	endFunc      defines.EndService
	callBackFunc defines.CallBack
}

func NewServerGo(name string) *ServiceGo {
	sg := &ServiceGo{
		Service: NewService(name),
	}
	return sg
}

func (sg *ServiceGo) Init() error {
	serverPath := "./gservice/" + sg.name + ".so"
	lib, err := purego.Dlopen(serverPath, purego.RTLD_LAZY|-purego.RTLD_LOCAL)
	if err != nil {
		return err
	}
	sg.libHandel = lib
	purego.RegisterLibFunc(&sg.startFunc, lib, "StartService")
	purego.RegisterLibFunc(&sg.runFunc, lib, "RunService")
	purego.RegisterLibFunc(&sg.endFunc, lib, "EndService")
	purego.RegisterLibFunc(&sg.callBackFunc, lib, "CallBack")
	return nil
}

func (sg *ServiceGo) Start() error {
	sg.startFunc()
	return nil
}

func (sg *ServiceGo) Run() error {
	go sg.runFunc()
	return nil
}

func (sg *ServiceGo) End() error {
	sg.endFunc()
	return nil
}
